package com.mall.common.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Pager;
import com.mall.common.domain.component.ComponentBundleDomain;
import com.mall.common.domain.component.ComponentDomain;
import com.mall.common.exception.NoticeException;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.ComponentBundleService;
import com.mall.common.service.ComponentService;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.IntRangeFieldValidator;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;

@Controller
@RequestMapping("/admin/system/component")
public class ComponentController extends BaseController  {
	
	@Resource private ComponentService componentService;
	@Resource private ComponentBundleService componentBundleService;
	
	/**
	 * 跳转到插件桩列表页面
	 * @return
	 */
	@RequestMapping(value="/type", method=RequestMethod.GET)
	public String type() {
    	return "/admin/system/component/type";
	}
	
	@RequestMapping("/queryBundleData")
	@ResponseBody
	public Pager queryBundleData(Pager pager) {
		pager = componentBundleService.findPage(pager);
		return JsonDataGridHelper.createJSONData(pager);
	}

	/**
	 * 校验插件类型名称
	 * @return
	 */
	@RequestMapping(value="/checkBundleName", method=RequestMethod.POST)
	@ResponseBody
	public String checkBundleName(String name, String oldValue){
		if (componentBundleService.isUnique("name", oldValue, name)) {
			return "true";
		} else {
			return "false";
		}
    }
	
	/**
	 * 保存插件桩
	 * @param componentBundle
	 * @return
	 */
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "name", message = "插件类型名称不能为空!"),
			@RequiredStringValidator(fieldName = "bundleId", message = "插件类型ID不能为空!")
		}
	)
	@RequestMapping(value="/saveBundle", method=RequestMethod.POST)
	public String saveBundle(ComponentBundleDomain componentBundle){
    	componentBundleService.persist(componentBundle);
    	return "redirect:type.jhtml";
    }
	
	/**
	 * 删除插件桩
	 * @return
	 */
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "id", message = "插件桩不存在!"),
		}
	)
	@RequestMapping(value="/deleteBundle", method=RequestMethod.POST)
	@ResponseBody
	public String deleteBundle(Long id, HttpServletResponse response){
    	componentBundleService.remove(id);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	/**
	 * 跳转到列表页面
	 * @return
	 */
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list() {
		return "/admin/system/component/list";
	}
	
	@RequestMapping(value="/queryData", method=RequestMethod.POST)
	@ResponseBody
	public Pager queryData(Pager pager){
		String hql=	"select c from ComponentDomain c order by c.componentBundle.createDate desc,c.orders";
		Finder finder = Finder.create(hql);		
		pager = componentService.findByPager(pager, finder);
		return JsonDataGridHelper.createJSONData(pager);
	}
	
	/**
	 * 跳转到新增页面
	 * @return
	 */
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String add(Model model){
		List<ComponentBundleDomain> bundleList = componentBundleService.getAll();
		model.addAttribute("bundleList", bundleList);
		return "/admin/system/component/input";
	}

	/**
	 * 校验插件名称
	 * @return
	 */
	@RequestMapping(value="/checkName", method=RequestMethod.POST)
	@ResponseBody
	public String checkName(ComponentDomain component, String oldValue){
		String newValue = component.getName();
		if (componentService.isUnique("name", oldValue, newValue)) {
			return "true";
		} else {
			return "false";
		}
    }
	
	/**
	 * 跳转到修改页面
	 * @return
	 */
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "id", message = "组件不存在!"),
		}
	)
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/edit", method=RequestMethod.GET)
	public String edit(Long id, Model model){
		List<ComponentBundleDomain> bundleList = componentBundleService.getAll();
		ComponentDomain component = componentService.find(id);
		if(component == null){
			throw new NoticeException("组件不存在!");
		}
		List<String> keyList = new ArrayList<String>();
		JSONObject config = component.getConfigJson(null);
		Iterator<String> it = config.keys();
		int groupNum = config.size(); 
		int paramNum = 0; 
		if(it.hasNext()){
			String key = it.next();
			JSONObject jobj = component.getConfigJson(key);
			paramNum += jobj.size();
			keyList.add(key);
		}
		String numInfo = groupNum + "," + paramNum;
		model.addAttribute("bundleList", bundleList);
		model.addAttribute("config", config);
		model.addAttribute("component", component);
		model.addAttribute("numInfo", numInfo);
		model.addAttribute("keyList", keyList);
		return "/admin/system/component/input";
	}
	
	/**
	 * 保存
	 * @return
	 */
	@Validations(
		requiredStrings = {
				@RequiredStringValidator(fieldName = "name", message = "组件名称不允许为空!"),
				@RequiredStringValidator(fieldName = "componentId", message = "插件ID不允许为空!"),
				@RequiredStringValidator(fieldName = "author", message = "组件作者不允许为空!"),
				@RequiredStringValidator(fieldName = "shopVersion", message = "系统版本不允许为空!"),
				@RequiredStringValidator(fieldName = "version", message = "组件版本不允许为空!")
		},
		requiredFields = {
			@RequiredFieldValidator(fieldName = "orders", message = "排序不允许为空!")				
		}, 
		intRangeFields = {
			@IntRangeFieldValidator(fieldName = "orders", min = "0", message = "排序必须为正整数!")			
		}
	)
	@RequestMapping(value="/save", method=RequestMethod.POST)
	public String save(ComponentDomain component, String paramStr, HttpServletResponse response){
		if(!componentService.isUnique("name", null, component.getName())){
			throw new NoticeException("组件名称重复");
		}
    	component.setConfig(paramStr);
        componentService.persist(component);
		return ResponseUtils.renderJSON(successMessage, response);
    }

	@Validations(
		requiredStrings = {
				@RequiredStringValidator(fieldName = "name", message = "组件名称不允许为空!"),
				@RequiredStringValidator(fieldName = "componentId", message = "插件ID不允许为空!"),
				@RequiredStringValidator(fieldName = "author", message = "组件作者不允许为空!"),
				@RequiredStringValidator(fieldName = "shopVersion", message = "系统版本不允许为空!"),
				@RequiredStringValidator(fieldName = "version", message = "组件版本不允许为空!")
		},
		requiredFields = {
			@RequiredFieldValidator(fieldName = "id", message = "组件不存在!"),
			@RequiredFieldValidator(fieldName = "orders", message = "排序不允许为空!")				
		}, 
		intRangeFields = {
			@IntRangeFieldValidator(fieldName = "orders", min = "0", message = "排序必须为正整数!")			
		}
	)
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(ComponentDomain component, String paramStr, HttpServletResponse response){
		if(!componentService.isUniqueById("name", component.getId(), component.getName())){
			throw new NoticeException("组件名称重复");
		}
		ComponentDomain current = componentService.find(component.getId());
		component.setConfig(paramStr);
		component.setInstallState(current.getInstallState());
		component.setEnableState(current.getEnableState());
		component.setErrormessage(current.getErrormessage());
		component.setPaymemtType(current.getPaymemtType());
		componentService.update(component);
		return ResponseUtils.renderJSON(successMessage, response);
	}

    /**
     * 安装插件
     * @return
     */
	@Validations(
		requiredFields = {
				@RequiredFieldValidator(fieldName = "id", message = "组件不存在!")
		}
	)
	@RequestMapping(value="/install", method=RequestMethod.POST)
	@ResponseBody
	public String install(Long id, HttpServletResponse response) {
	    componentService.install(id);
		return ResponseUtils.renderJSON(successMessage, response);
	}

	/**
	 * 卸载插件
	 * @return
	 */
	@Validations(
		requiredFields = {
				@RequiredFieldValidator(fieldName = "id", message = "组件不存在!")
		}
	)
	@RequestMapping(value="/unInstall", method=RequestMethod.POST)
	@ResponseBody
	public String unInstall(Long id, HttpServletResponse response) {
		componentService.unInstall(id);
		return ResponseUtils.renderJSON(successMessage, response);
	}

	/**
	 * 启用插件
	 * @return
	 */

	@Validations(
		requiredFields = {
				@RequiredFieldValidator(fieldName = "id", message = "组件不存在!")
		}
	)
	@RequestMapping(value="/start", method=RequestMethod.POST)
	@ResponseBody
	public String start(Long id, HttpServletResponse response) {
		componentService.start(id);
		return ResponseUtils.renderJSON(successMessage, response);
	}

	/**
	 * 停用插件
	 * @return
	 */

	@Validations(
		requiredFields = {
				@RequiredFieldValidator(fieldName = "id", message = "组件不存在!")
		}
	)
	@RequestMapping(value="/stop", method=RequestMethod.POST)
	@ResponseBody
	public String stop(Long id, HttpServletResponse response) {
		componentService.stop(id);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
}
